package com.example.spring.boot.rabbitmq.service;

import com.example.spring.boot.rabbitmq.constant.DelayExchangeConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * <p>
 * DelaySenderService
 * </p>
 *
 * @author weixin
 * @date 2023/3/28 14:53
 */
@Slf4j
@Service
public class DelaySenderService {

    @Resource
    private RabbitTemplate rabbitTemplate;

    /**
     *  发送延迟消息
     * @param payload {@link String} json消息
     * @param delayTime {@link Integer} 延迟时间
     */
    public void sendDelayMessage(String payload, int delayTime) {
        rabbitTemplate.convertAndSend(DelayExchangeConstant.DELAY_EXCHANGE,
                DelayExchangeConstant.DELAY_ROUTING_KEY,
                payload,
                message -> {
                    // 延迟时间单位是毫秒
                    message.getMessageProperties().setDelay(delayTime);
                    log.info("DelaySenderService.sendDelayMessage, 消息发送时间: {}, 消息内容: {}",
                            LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyy-MM-dd HH:mm:ss")),
                            payload);
                    return message;
                });
    }

}
